package com.pc_project.domain.authenticate;

import com.alibaba.fastjson.annotation.JSONField;
import com.pc_project.domain.User;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@NoArgsConstructor
public class UserAuthenticator implements UserDetails {
    private User user;

    public UserAuthenticator(User user) {
        this.user = user;
    }

    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //        如果authorities权限信息集合不为空，那么我们就直接返回。
        if (authorities != null) {
            return authorities;
        }
        SimpleGrantedAuthority authority = new SimpleGrantedAuthority(user.getRole());
//        这里记得如果不用函数式编程，那么就要new一个数组集合，不然就会空报错。
        authorities = new ArrayList<GrantedAuthority>();
        authorities.add(authority);
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getPassword();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
